package cn.haulon.express.kuaidi100;

import cn.haulon.express.Express;
import cn.haulon.express.ExpressFactory;
import com.alibaba.fastjson.JSON;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Haulon on 09/01/2018.
 * <p>
 * Used as 快递100查询服务
 */
public class Kuaidi100Service implements Express {
    private static final Kuaidi100Code code = new Kuaidi100Code();
    private static final Kuaidi100Express express = (Kuaidi100Express) ExpressFactory.getServer(Kuaidi100Express.class);

    @Override
    public Map<String, Object> query(String number) {
        Object result = express.query(number);
        return formatResult((String) result);
    }

    @Override
    public Map<String, Object> query(String type, String number) {
        Object result = express.query(type, number);
        return formatResult((String) result);
    }

    private Map<String, Object> formatResult(String result) {
        Map<String, Object> map = jsonStrToMap(result);
        if (map != null && !map.isEmpty()) {
            map.put("comName", getCompanyName((String) map.get("com"), (String) map.get("nu")));
        }
        return map == null ? new HashMap<>() : map;
    }

    private Map<String, Object> jsonStrToMap(String json) {
        return JSON.parseObject(json);
    }

    private String getCompanyName(String companyCode, String number) {
        String companyName = code.getName(companyCode);
        if (companyName == null) {
            companyName = express.getCompanyName(number);
            code.set(companyCode, companyName);
        }
        return companyName;
    }

    public static void main(String[] args) {
        System.out.println(ExpressFactory.getServer(Kuaidi100Service.class).query("888793503397"));
    }
}
